package com.hzz.service.patrol;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzz.api.patrol.IPatrolTaskService;
import com.hzz.dao.patrol.IPatrolTaskDao;
import com.hzz.dao.river.IRiverInfoDao;
import com.hzz.dto.patrol.PatrolStatDto;
import com.hzz.dto.patrol.PatrolTaskDto;
import com.hzz.dto.patrol.TaskLogDto;
import com.hzz.dto.river.RiverInfoDto;
import com.hzz.entity.patrol.PatrolTask;
import com.hzz.entity.river.RiverInfo;
import com.hzz.framework.Response;
import com.hzz.framework.SysErrorCode;
import com.hzz.framework.annotation.FeignService;
import com.hzz.framework.exception.ServiceException;
import com.hzz.framework.service.BaseService;
import com.hzz.framework.util.CommonConstant;
import com.hzz.framework.util.IdUtil;
import com.hzz.framework.util.ValidatorUtil;
import com.hzz.service.dsync.PatrolTaskDSync;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@FeignService
@Slf4j
public class PatrolTaskService extends BaseService implements IPatrolTaskService {
    @Autowired
    IPatrolTaskDao patrolTaskDao;

    @Autowired
    PatrolTaskDSync patrolTaskDSync;
    @Autowired
    IRiverInfoDao riverInfoDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = CommonConstant.DB_DEFAULT_TIMEOUT, rollbackFor = {
            Exception.class, RuntimeException.class})
    public Response saveOrUpdateData(PatrolTaskDto dto) throws Exception {
        Response result = new Response(0, "success");
        try {
            PatrolTask entity = copyTo(dto, PatrolTask.class);
            // 判断数据是否存在
            if (patrolTaskDao.isDataExist(entity) != 0) {
                // 数据存在
                result.data = patrolTaskDao.update(entity);
            } else {
                // 新增
                if (entity.getId() == null) {
                    entity.setId(IdUtil.nextId());
                }
                if (!ValidatorUtil.notEmpty(entity.getAreaIds()) && ValidatorUtil.notEmpty(entity.getRiverCourseCode())) {
                    RiverInfo riverEntity = new RiverInfo();
                    riverEntity.setId(Long.parseLong(entity.getRiverCourseCode()));
                    RiverInfo riverInfo = (RiverInfo) riverInfoDao.selectByPrimaryKey(riverEntity);
                    if (riverInfo != null) {
                        entity.setRiverCourseName(riverInfo.getName());
                        entity.setAreaIds(riverInfo.getAreaIds());
                        entity.setAreaNames(riverInfo.getAreaNames());
                        entity.setPac(riverInfo.getPac());
                        entity.setCreatorLevel(riverInfo.getLevel());
                    }
                }
                patrolTaskDao.insert(entity);
                result.data = entity.getId();
            }
            if (CommonConstant.TASK_STATUS_巡查任务_已巡查.equals(entity.getTaskStatus())) {
                // dsync
                taskExecutor.execute(() -> {
                    try {
                        Thread.sleep(5 * 1000);// 等5秒再推送
                        patrolTaskDSync.patrolTaskRecord(entity);
                    } catch (Exception e) {
                        log.error("巡查任务_已巡查",e);
                    }
                });
            }
        } catch (Exception e) {
            log.error("信息保存异常!", e);
            throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
        }
        return result;
    }

    @Override
    public String deleteData(PatrolTaskDto dto) throws Exception {
        String result = "success";
        try {
            PatrolTask entity = copyTo(dto, PatrolTask.class);
            if (patrolTaskDao.deleteByPrimaryKey(entity) == 0) {
                throw new RuntimeException("数据不存在!");
            }
        } catch (Exception e) {
            log.error("物理删除异常!", e);
            throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
        }
        return result;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = CommonConstant.DB_DEFAULT_TIMEOUT, rollbackFor = {
            Exception.class, RuntimeException.class})
    public String deleteDataById(PatrolTaskDto dto) throws Exception {
        String result = "success";
        try {
            PatrolTask entity = copyTo(dto, PatrolTask.class);
            if (patrolTaskDao.deleteById(entity) == 0) {
                throw new RuntimeException("数据不存在!");
            }
        } catch (Exception e) {
            log.error("逻辑删除异常!", e);
            throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
        }
        return result;
    }

    @Override
    public PageInfo findDataIsPage(PatrolTaskDto dto) throws Exception {
        PageInfo pageInfo = null;
        try {
            PatrolTask entity = copyTo(dto, PatrolTask.class);
            PageHelper.startPage(PN(dto.getPageNum()), PS(dto.getPageSize()));
            List list = patrolTaskDao.findDataIsPage(entity);
            pageInfo = new PageInfo(list);
            pageInfo.setList(copyTo(pageInfo.getList(), PatrolTaskDto.class));
        } catch (Exception e) {
            log.error("信息[分页]查询异常!", e);
            throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
        }
        return pageInfo;
    }

    @Override
    public List<PatrolTaskDto> findDataIsList(PatrolTaskDto dto) throws Exception {
        List<PatrolTaskDto> results = null;
        try {
            PatrolTask entity = copyTo(dto, PatrolTask.class);
            results = copyTo(patrolTaskDao.findDataIsList(entity), PatrolTaskDto.class);
        } catch (Exception e) {
            log.error("信息[列表]查询异常!", e);
            throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
        }
        return results;
    }

    @Override
    public PatrolTaskDto findDataById(PatrolTaskDto dto) throws Exception {
        PatrolTaskDto result = null;
        try {
            PatrolTask entity = copyTo(dto, PatrolTask.class);
            result = copyTo(patrolTaskDao.selectByPrimaryKey(entity), PatrolTaskDto.class);
        } catch (Exception e) {
            log.error("信息[详情]查询异常!", e);
            throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
        }
        return result;
    }

    @Override
    public List<PatrolTaskDto> findListByParam(PatrolTaskDto dto) throws Exception {
        List<PatrolTaskDto> results = null;
        try {
            PatrolTask entity = copyTo(dto, PatrolTask.class);
            entity.setAreaIds(entity.getAreaIds());
            if (StringUtils.isNotBlank(entity.getAreaIds())) {
                String temp = entity.getAreaIds();
                while (temp.endsWith(",")) {
                    temp = temp.substring(0, temp.length() - 1);
                }
                entity.setAreaIdsSub(temp);
            }
            results = copyTo(patrolTaskDao.findListByParam(entity), PatrolTaskDto.class);
        } catch (Exception e) {
            log.error("信息[列表]查询异常!", e);
            throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
        }
        return results;
    }

    @Override
    public PageInfo findListByParamPage(PatrolTaskDto dto) throws Exception {
        PageInfo pageInfo = null;
        try {
            PatrolTask entity = copyTo(dto, PatrolTask.class);
            PageHelper.startPage(PN(dto.getPageNum()), PS(dto.getPageSize()));
            entity.setAreaIds(entity.getAreaIds());
            if (StringUtils.isNotBlank(entity.getAreaIds())) {
                String temp = entity.getAreaIds();
                while (temp.endsWith(",")) {
                    temp = temp.substring(0, temp.length() - 1);
                }
                entity.setAreaIdsSub(temp);
            }
            pageInfo = new PageInfo(patrolTaskDao.findListByParam(entity));
            pageInfo.setList(copyTo(pageInfo.getList(), PatrolTaskDto.class));
        } catch (Exception e) {
            log.error("信息[分页]查询异常!", e);
            throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
        }
        return pageInfo;
    }

    @Override
    public PageInfo findCompletionStatistics(PatrolTaskDto dto) throws Exception {
        PageInfo pageInfo = null;
        try {
            PatrolTask entity = copyTo(dto, PatrolTask.class);
            PageHelper.startPage(PN(dto.getPageNum()), PS(dto.getPageSize()));
            List list = patrolTaskDao.findCompletionStatistics(entity);
            pageInfo = new PageInfo(list);
            pageInfo.setList(copyTo(pageInfo.getList(), TaskLogDto.class));
        } catch (Exception e) {
            log.error("完成情况统计[分页]查询异常!", e);
            throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
        }
        return pageInfo;
    }

    @Override
    public PageInfo findPatrolTaskLog(PatrolTaskDto dto) throws Exception {
        PageInfo pageInfo = null;
        try {
            PatrolTask entity = copyTo(dto, PatrolTask.class);
            if (entity.getAreaIds() != null) {
                entity.setAreaIds(entity.getAreaIds());
            }
            PageHelper.startPage(PN(dto.getPageNum()), PS(dto.getPageSize()));
            List list = patrolTaskDao.findPatrolTaskLog(entity);
            pageInfo = new PageInfo(list);
            pageInfo.setList(copyTo(pageInfo.getList(), TaskLogDto.class));
        } catch (Exception e) {
            log.error("本级河长日志[分页]查询异常!", e);
            throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
        }
        return pageInfo;
    }

    @Override
    public PageInfo findPatrolTaskLogJunior(PatrolTaskDto dto) throws Exception {
        PageInfo pageInfo = null;
        try {
            PatrolTask entity = copyTo(dto, PatrolTask.class);
            if (entity.getAreaIds() != null) {
                entity.setAreaIds(entity.getAreaIds());
            }
            PageHelper.startPage(PN(dto.getPageNum()), PS(dto.getPageSize()));
            List list = patrolTaskDao.findPatrolTaskLogJunior(entity);
            pageInfo = new PageInfo(list);
            pageInfo.setList(copyTo(pageInfo.getList(), TaskLogDto.class));
        } catch (Exception e) {
            log.error("下级河长日志[分页]查询异常!", e);
            throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
        }
        return pageInfo;
    }

    @Override
    public List findPatrolTaskLogList(PatrolTaskDto dto) throws Exception {
        List list = null;
        try {
            PatrolTask entity = copyTo(dto, PatrolTask.class);
            if (entity.getAreaIds() != null) {
                entity.setAreaIds(entity.getAreaIds());
            }
            list = patrolTaskDao.findPatrolTaskLog(entity);
        } catch (Exception e) {
            log.error("本级河长日志[列表]查询异常!", e);
            throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
        }
        return list;
    }

    @Override
    public List findPatrolTaskLogListJunior(PatrolTaskDto dto) throws Exception {
        List list = null;
        try {
            PatrolTask entity = copyTo(dto, PatrolTask.class);
            if (entity.getAreaIds() != null) {
                entity.setAreaIds(entity.getAreaIds());
            }
            list = patrolTaskDao.findPatrolTaskLogJunior(entity);
        } catch (Exception e) {
            log.error("下级河长日志[分页]查询异常!", e);
            throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
        }
        return list;
    }

    @Override
    public Integer getPatrolTimes(PatrolTaskDto dto) throws Exception {
        Integer result = 0;
        try {
            PatrolTask entity = copyTo(dto, PatrolTask.class);
            // 验证参数河道id,巡查人账号，开始、结束时间
            if (StringUtils.isBlank(entity.getRiverCourseCode())) {
                throw new ServiceException(SysErrorCode.defaultError, "参数[河道id]为空");
            }
            if (StringUtils.isBlank(entity.getExecutorAccount())) {
                throw new ServiceException(SysErrorCode.defaultError, "参数[巡查人账号]为空");
            }
            if (entity.getStartTime() == null || entity.getEndTime() == null) {
                throw new ServiceException(SysErrorCode.defaultError, "参数[开始时间或结束时间]为空");
            }
            result = patrolTaskDao.getPatrolTimes(entity);
        } catch (Exception e) {
            log.error("app接口查询巡查次数 查询异常!", e);
            throw new ServiceException(SysErrorCode.defaultError, e.getMessage());
        }
        return result;
    }

    @Override
    public List patrolStat(PatrolStatDto dto) throws Exception {
        return patrolTaskDao.patrolStat(dto);
    }

    @Override
    public PageInfo patrolStatTable(PatrolStatDto dto) throws Exception {
        PageHelper.startPage(PN(dto.getPageNum()), PS(dto.getPageSize()));
        List list = patrolTaskDao.patrolStat(dto);
        return new PageInfo(list);
    }

    @Override
    public List<HashMap> getInspectionRateDESC() throws Exception {
        return patrolTaskDao.getInspectionRateDESC();
    }

    @Override
    public List<HashMap> getInspectionRateASC() throws Exception {
        return patrolTaskDao.getInspectionRateASC();
    }

    @Override
    public List<PatrolTaskDto> getList(PatrolTaskDto dto) throws Exception {
        return patrolTaskDao.getList(dto);
    }
}
